package com.example.nophase.Fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.transition.Slide;
import android.transition.TransitionManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.nophase.R;
import com.example.nophase.activity.finance.WorkDetailFormActivity;
import com.example.nophase.adapter.InstructionsAdapter;
import com.example.nophase.api.RequstCommonApi;
import com.example.nophase.base.BaseFragment;
import com.example.nophase.common.BaseCallBack;
import com.example.nophase.common.BaseResp;
import com.example.nophase.entity.A;
import com.example.nophase.entity.InstructionsDTO;
import com.example.nophase.entity.RecordsDTO;
import com.example.nophase.utils.HttpUtils;
import com.example.nophase.utils.MessageEvent;
import com.example.nophase.utils.StringTool;
import com.example.nophase.utils.TLiveConfig;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Response;

public class InstructionsFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    private static final String ARG_POSITION = "position";
    @BindView(R.id.dummyfrag_scrollableview)
    RecyclerView recyclerView;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.progress_layout)
    FrameLayout mFrameLayout;
    @BindView(R.id.select)
    Button select;
    @BindView(R.id.delete)
    Button delete;
    @BindView(R.id.cancel)
    Button cancel;
    @BindView(R.id.ll_slide)
    LinearLayout mLayoutSlide;
    @BindView(R.id.iv_background)
    ImageView iv_background;


    private int position;
    private InstructionsAdapter recyclerAdapter;
    private int delayMillis = 300;
    private int pegNum = TLiveConfig.COMMON_PAGE_NUM;
    private int startIndex = TLiveConfig.COMMON_PAGE_START;
    private boolean isRefresh;
    private boolean isLoadMore;
    private boolean isItemSelected;
    private boolean mLoadMoreEndGone = true;
    private boolean isOpen;
    private List<InstructionsDTO> resultListBeen = new ArrayList<>();
    private List<InstructionsDTO> listCheck = new ArrayList<>();
    private int totalCounter = 0;
    public String status;
    public static InstructionsFragment newInstance(int position) {
        InstructionsFragment f = new InstructionsFragment();
        Bundle b = new Bundle();
        b.putInt(ARG_POSITION, position);
        f.setArguments(b);
        return f;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        position = getArguments().getInt(ARG_POSITION);
        Log.d("TAG", "onCreate: " + position);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(MessageEvent messageEvent) {
        if (!isOpen) {
            isOpen = true;
            recyclerAdapter.openItemAnimation();
            setSlide(mLayoutSlide);


        }
    }

    @Override
    protected void initView(Bundle savedInstanceState, View view) {
        ButterKnife.bind(InstructionsFragment.this, view);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.instructions_fragment_layout;
    }

    @Override
    protected View getLoadingTargetView() {
        return mFrameLayout;
    }

    @Override
    protected void initData() {
        initAdapter();
        onAutoRefresh();
    }

    private void onAutoRefresh() {
        mSwipeRefreshLayout.setRefreshing(true);
        onRefresh();
    }

    private void initAdapter() {

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setHasFixedSize(true);
        recyclerAdapter = new InstructionsAdapter(getActivity(), resultListBeen);
        recyclerAdapter.openLoadAnimation();
        recyclerAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);

        recyclerAdapter.setOnLoadMoreListener(this, recyclerView);

        recyclerView.setAdapter(recyclerAdapter);
//        自定义loading 样式
        mSwipeRefreshLayout.setOnRefreshListener(this);

        recyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<InstructionsDTO> resultListBeen = adapter.getData();
                Intent intent = new Intent(getActivity(), WorkDetailFormActivity.class);
                intent.putExtra("forkey",String.valueOf(resultListBeen.get(position).getId()));
                intent.putExtra("type","财务");
                startActivity(intent);

//                if (StringTool.isListValidate(resultListBeen)) {
//                    if (isOpen) {
//                        return;
//                    }
//
//                }
            }

            @Override
            public void onItemLongClick(BaseQuickAdapter adapter, View view, int position) {


            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                List<InstructionsDTO> resultListBeen = adapter.getData();
                InstructionsDTO resultBean = resultListBeen.get(position);
                CheckBox checkbox = view.findViewById(R.id.item_checkbox);
                if (!checkbox.isChecked()) {
                    resultBean.setChecked(true);
                    listCheck.add(resultBean);
                } else {
                    resultBean.setChecked(false);
                    listCheck.remove(resultBean);
                }

            }

        });
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                showCheckedDialog();


            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isOpen) {
                    isOpen = false;
                    recyclerAdapter.closeItemAnimation();
                    setSlide(mLayoutSlide);
                }
            }
        });
        select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isOpen) {
                    List<InstructionsDTO> resultListBeen = recyclerAdapter.getData();
                    listCheck.clear();
                    for (int i = 0; i < recyclerAdapter.getData().size(); i++) {
                        InstructionsDTO resultBean = resultListBeen.get(i);
                        resultBean.setChecked(true);
                        listCheck.add(resultBean);
                    }

                    recyclerAdapter.notifyDataSetChanged();
                }

            }
        });

    }


    private void showCheckedDialog() {
        String[] namelist = {"已支付", "已报销"};
        String[] name = new String[1];
        status = namelist[0];
        new AlertDialog.Builder(getActivity())
                .setTitle("请选择批付方式")//提示框标题
                .setIcon(R.drawable.apply_for_from)
                .setSingleChoiceItems(
                        namelist, 0,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                status = namelist[which];
                                Toast.makeText(getActivity(), "选择了" + namelist[which], Toast.LENGTH_LONG).show();
                            }
                        }

                )
                .setPositiveButton("确定",//提示框的两个按钮
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                save();

                            }
                        })

                .setNegativeButton("取消", null).create().show();
    }

    public void save() {
        List<InstructionsDTO> resultList = recyclerAdapter.getData();
        for (InstructionsDTO item : listCheck) {
            item.setAccoutFinalStatus(status);
        }
        A apply = new A();
        apply.setTyBusinessAppList(listCheck);
        Call<BaseResp<Object>> call = HttpUtils.getInstance().getApiService(RequstCommonApi.class).saveInstructions("ANDROID",apply);
        call.enqueue(new BaseCallBack<BaseResp<Object>>() {
            @Override
            public void onSuccess(Response<BaseResp<Object>> response) throws Exception {

                String code = response.body().getCode();
                boolean success = response.body().getSuccess();
                if (code.equals("200") && success) {
                    Toast.makeText(getActivity(), "审批完成", Toast.LENGTH_LONG).show();

                    if (isOpen) {
                        int length = resultList.size();
                        for (int i = length - 1; i >= 0; i--) {
                            InstructionsDTO resultListBean = resultList.get(i);
                            if (resultListBean.getChecked()) {
                                listCheck.remove(resultListBean);
                                resultList.remove(i);
                                recyclerAdapter.notifyItemRemoved(i);
                                recyclerAdapter.notifyItemRangeChanged(0, resultList.size());
                            }
                        }

                        recyclerAdapter.notifyDataSetChanged();
                    }


                    if (isOpen) {
                        isOpen = false;
                        recyclerAdapter.closeItemAnimation();
                        setSlide(mLayoutSlide);
                    }

                }
            }

            @Override
            public void onFailure(String message) {

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (resultCode) {

            case TLiveConfig.ACTION_NAME:
                onAutoRefresh();
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    public void onRefresh() {

        recyclerAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isRefresh = true;
                startIndex = TLiveConfig.COMMON_PAGE_START;
                recyclerAdapter.getData().clear();
                Call<BaseResp<RecordsDTO<InstructionsDTO>>> call = HttpUtils.getInstance().getApiService(RequstCommonApi.class).loadBatchOfPayno("ANDROID",50, startIndex);
                call.enqueue(new BaseCallBack<BaseResp<RecordsDTO<InstructionsDTO>>>() {
                    @Override
                    public void onSuccess(Response<BaseResp<RecordsDTO<InstructionsDTO>>> response) throws Exception {
                        List<InstructionsDTO> list = response.body().getData().getRecords();
                        isRefresh = false;
                        onNext(list);
                    }

                    @Override
                    public void onFailure(String message) {

                    }
                });

                recyclerAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);
    }


    @Override
    public void onLoadMoreRequested() {
        mSwipeRefreshLayout.setEnabled(false);
        recyclerView.postDelayed(new Runnable() {
            @Override
            public void run() {

                if (startIndex >= totalCounter) {
                    recyclerAdapter.loadMoreEnd();//default visible
                    recyclerAdapter.loadMoreEnd(mLoadMoreEndGone);//true is gone,false is visible
                } else {

                    startIndex += pegNum;
                    isLoadMore = true;
                    Call<BaseResp<RecordsDTO<InstructionsDTO>>> call = HttpUtils.getInstance().getApiService(RequstCommonApi.class).loadBatchOfPayno("ANDROID",50, startIndex);
                    call.enqueue(new BaseCallBack<BaseResp<RecordsDTO<InstructionsDTO>>>() {
                        @Override
                        public void onSuccess(Response<BaseResp<RecordsDTO<InstructionsDTO>>> response) throws Exception {

                            List<InstructionsDTO> list = response.body().getData().getRecords();

                            isRefresh = false;
                            onNext(list);
                        }

                        @Override
                        public void onFailure(String message) {

                        }
                    });
                    //加载完成
                    recyclerAdapter.loadMoreComplete();
                }
                mSwipeRefreshLayout.setEnabled(true);
            }

        }, delayMillis);
    }


    private void setSlide(LinearLayout linearLayout) {
        int finalState = linearLayout.getVisibility() == View.VISIBLE ? View.INVISIBLE : View.VISIBLE;

        if (Build.VERSION.SDK_INT < 21) {
            linearLayout.setVisibility(finalState);
        } else {
            Slide slide = new Slide();
            slide.setSlideEdge(Gravity.BOTTOM);

            final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) getActivity()
                    .findViewById(android.R.id.content)).getChildAt(0);
            TransitionManager.beginDelayedTransition(viewGroup, slide);

            linearLayout.setVisibility(finalState);
        }
    }


    public void onNext(List<InstructionsDTO> nodeList) {

        if(nodeList.size()> 0){
            iv_background.setVisibility(View.GONE);
        }
        if (isItemSelected) {
            listCheck.clear();
            resultListBeen.clear();
            isItemSelected = false;
            recyclerAdapter.notifyDataSetChanged();
            if (StringTool.isListValidate(nodeList)) {
                recyclerAdapter.setNewData(nodeList);
            }

        } else {
            if (isRefresh) {
                listCheck.clear();
                resultListBeen.clear();
                isRefresh = false;
                recyclerAdapter.notifyDataSetChanged();
                if (StringTool.isListValidate(nodeList)) {
                    recyclerAdapter.setNewData(nodeList);
                } else {
                    recyclerAdapter.setEmptyView(getActivity().
                            getLayoutInflater().inflate(R.layout.empty_view,
                            (ViewGroup) recyclerView.getParent(), false));
                }

                mSwipeRefreshLayout.setRefreshing(false);
            } else {
                if (StringTool.isListValidate(nodeList)) {
                    recyclerAdapter.addData(nodeList);
                } else if (!isLoadMore) {
                    recyclerAdapter.setEmptyView(getActivity().
                            getLayoutInflater().inflate(R.layout.empty_view,
                            (ViewGroup) recyclerView.getParent(), false));
                }
            }
        }

        mSwipeRefreshLayout.setRefreshing(false);


    }



    @Override
    protected void OnClick(View v) {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if(EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }



}
